require "log"
require "http"
require "mqtt"
require "config"
require "misc"
require "hwOutMsg"
require "hwInMsg"
require "httpsGet"

module(..., package.seeall)

local ready = false

function isReady() return ready end

local function keyGenerate(key)
    local clk = os.date("*t", os.time()) -- 获取UTC时间的table
    local timeStr = string.format("%02d%02d%02d%02d", clk.year, clk.month,
                                  clk.day, clk.hour) -- 时间戳
    local result = crypto.hmac_sha256(key, timeStr):lower()
    log.info("keyGenerate", timeStr, key, result)
    if crypto.hmac_sha256 then
        return result
    else
        log.error("crypto.hmac_sha256",
                  "please update your lod version, higher than 0034!")
        rtos.poweroff()
    end
end

local function startHWMqtt()
    sys.taskInit(function()
        local retryConnectCnt = 0
        local errorCnt = 0
        sys.wait(6000)

        if socket.isReady() == false then
            retryConnectCnt = 0
            sys.waitUntil("IP_READY_IND", 300000)
        end

        if socket.isReady() == true and nvm.get("HW_REGISTER") == 0 then
            -- 第一次启动，先获取一次设备SECRET
            sys.wait(2000)
            httpsGet.hw_http_getToken()
            sys.waitUntil("HW_GETTOKEN", 5000)
            httpsGet.hw_http_register()
            sys.waitUntil("HW_REGISTER", 10000)
        end

        while true do
            if socket.isReady() == false then
                retryConnectCnt = retryConnectCnt + 1
                sys.waitUntil("IP_READY_IND", 300000)
            end

            if socket.isReady() == true and nvm.get("HW_REGISTER") == 1 then

                local clk = os.date("*t", os.time()) -- 获取UTC时间的table
                local username = config.HW_DEV_PRODUCTID .. "_GWRD_" ..
                                     misc.getImei()
                -- local clientID = username .. "_0_0_" .. string.format("%02d%02d%02d%02d", clk.year, clk.month, clk.day, clk.hour)
                local clientID = username
                local mqttClient = mqtt.client(clientID, 120, username,
                                               config.HW_SECRET)

                local topo_change = "$oc/devices/" .. username ..
                                        "/sys/events/down"
                local command_topic = "$oc/devices/" .. username ..
                                          "/sys/commands/"

                log.info("USERNAME", username)
                log.info("CIENTID", clientID)
                log.info("SECRET", config.HW_SECRET)
                -- log.info("result", mqttClient:connect("iot-device.wens.com.cn", 1883, "tcp"))
                -- while not mqttClient:connect("iot-device.wens.com.cn", 1883, "tcp") do
                --    sys.wait(2000)
                -- end
                if mqttClient:connect("iot-device.wens.com.cn", 1883, "tcp") then
                    -- mqttClient:subscribe(topo_change)
                    mqttClient:subscribe(command_topic .. "#")

                    log.info("mqtt.task", "mqtt success to connect huaweiyun")
                    sys.publish("HW_MQTT_READY", true)
                    retryConnectCnt = 0
                    ready = true

                    while true do
                        if not hwOutMsg.proc(mqttClient) then
                            break
                        end
                        if not hwInMsg.proc(mqttClient) then
                            break
                        end
                    end

                    ready = false
                else
                    log.info("mqtt.task", "HW mqtt FAILED")
                    -- retryConnectCnt = retryConnectCnt + 1
                    errorCnt = errorCnt + 1
                    log.info("CONNECT ERROR", errorCnt)
                end

                -- if retryConnectCnt >= 5 then
                --     link.shut()
                --     retryConnectCnt = 0
                -- end
                sys.wait(5000)
            else
                net.switchFly(true)
                sys.wait(20000)
                net.switchFly(false)
            end

            if errorCnt > 200 or retryConnectCnt > 15 then
                sys.restart("NET_ERROR_REBOOT|" .. tool.miscTime())
            end

        end

    end)
end

startHWMqtt()
